//
//  ChildListViewController.m
//  XMLY
//
//  Created by lanou on 15/11/7.
//  Copyright © 2015年 曾杰. All rights reserved.
//

#import "ChildListViewController.h"
#import "PKRequestManager.h"
#import "ChildDetailModel.h"
#import "ChildCell.h"
#import "MJRefresh.h"
#import "CheckNetConnect.h"
#import "NetConnectView.h"
#import "MusicDetailViewController.h"
@interface ChildListViewController ()<UITableViewDataSource, UITableViewDelegate>
@property (nonatomic, strong) UITableView *mainTableView;
@property (nonatomic, strong) NSMutableArray *dataSourceArr;
@property (nonatomic, strong) NSMutableDictionary *parDic;
@property (nonatomic, strong) NetConnectView *connectView;
@property (nonatomic, assign) NSInteger count;
@end

@implementation ChildListViewController

- (NSMutableArray *)dataSourceArr{
    if (_dataSourceArr == nil) {
        _dataSourceArr = [NSMutableArray array];
    }
    return _dataSourceArr;
}
- (void)requestData{
    NSString *str = [@"pageId=" stringByAppendingString:[NSString stringWithFormat:@"%ld", (long)_count]];
    NSRange rang = [self.urlStr rangeOfString:@"pageId=1"];
    NSString *newUrlStr = [self.urlStr stringByReplacingCharactersInRange:rang withString:str];
    
    
    [PKRequestManager requestWithType:GET urlString:newUrlStr parDic:nil finish:^(NSData *data) {
       
                       NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves) error:nil];
        
                NSString * totalCount = [dic objectForKey:@"totalCount"];
                for (NSDictionary *dic1 in dic[@"list"]) {
                    ChildDetailModel *model = [[ChildDetailModel alloc] init];
                    [model setValuesForKeysWithDictionary:dic1
                     ];
                    [model setValue:totalCount forKey:@"totalCount"];
                    [self.dataSourceArr addObject:model];
                }
                
                [self.mainTableView reloadData];
                
                [self.mainTableView.footer endRefreshing];
        
    } error:^(NSError *error) {
        NSLog(@"%@", [error localizedDescription]);
    }];
                   
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.parDic = [NSMutableDictionary dictionary];
    self.mainTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 70) style:(UITableViewStylePlain)];
    _mainTableView.dataSource = self;
    _mainTableView.delegate = self;
    _mainTableView.rowHeight = 120;
    
    [_mainTableView registerClass:[ChildCell class] forCellReuseIdentifier:@"cell"];
    [self.view addSubview:_mainTableView];
    _count = 1;
    // 检查网络连接
    [self checkNetConnectState];
//    [self requestData];
   
    
    __weak typeof(self) weakSelf = self;
    self.mainTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        //        [weakSelf requestData];
        [weakSelf checkNetConnectState];
     
        [self.mainTableView.header endRefreshing];
        
    }];
    self.mainTableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        //        [weakSelf requestData];
        _count ++;
        [weakSelf checkNetConnectState];
    }];

    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)checkNetConnectState{
    
    BOOL netState = [[CheckNetConnect shareConnect] netConnectState];
    NSLog(@"+++%d", netState);
    if (netState == YES) {
        NSLog(@"开始刷新数据");
        _connectView.frame = CGRectMake(0, - SCREEN_HEIGHT - 20, SCREEN_WIDTH, SCREEN_HEIGHT - 50) ;
        [_connectView.retryBtn addTarget:self action:@selector(retryRequest) forControlEvents:(UIControlEventTouchUpInside)];
        _count ++;
        [self requestData];
        
    }else{
        
        _connectView = [[NetConnectView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 50)];
        [_connectView.retryBtn addTarget:self action:@selector(retryRequest) forControlEvents:(UIControlEventTouchUpInside)];
        
        [self.view addSubview:_connectView];
    }
    
}
// 重新请求数据
- (void)retryRequest{
     NSLog(@"重新刷新数据");
    [self checkNetConnectState];
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.dataSourceArr.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ChildCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.frame = CGRectMake(0, 0, SCREEN_WIDTH, 110);
    ChildDetailModel *model = self.dataSourceArr[indexPath.row];
    if (self.dataSourceArr.count==[model.totalCount integerValue]) {
        [self.mainTableView.footer noticeNoMoreData];
    }
    [cell configureCellWithModel:model];
    // Configure the cell...
    
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    ChildDetailModel *model = self.dataSourceArr[indexPath.row];
    MusicDetailViewController *childListVC = [[MusicDetailViewController alloc] init];
    childListVC.albumId =[NSString stringWithFormat:@"%ld",(NSInteger)model.albumId ];
    [self presentViewController:childListVC animated:YES completion:nil];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
